package com.zl.smartmall.library;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.listener.AlipayPayListener;
import com.zl.smartmall.library.listener.WechatPayListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

import android.content.Context;

/**
 * 支付相关操作接口
 * @author 陈希然
 *
 */
public class IPay {

	private static final String TAG = IPay.class.getSimpleName();
	private static IPay mInstance;
	private static Lock mLock;
	private Context mContext;
	
	static{
		mLock = new ReentrantLock();
	}
	
	private IPay(Context context) {
		mContext = context;
	}
	
	public static IPay getInstance() {
		return mInstance;
	}
	
	public static void init(Context context) {
		if(mInstance == null){
    		mLock.lock();
    		try{
				if(mInstance == null){
					mInstance = new IPay(context);
				}
    		}finally{
    			mLock.unlock();
    		}
    	}
	}
	
	/**
	 * 获取支付宝支付数据
	 * @param orderCode 订单号
	 * @param alipayPayListener 回调监听器
	 */
	public void alipayPay(String orderCode, AlipayPayListener alipayPayListener) {
		if(!Tools.hasInternetConnection(mContext)) {
			alipayPayListener.onNoNetWork();
			
		}else {
			RequestParams params = new RequestParams();
			params.put("sn", orderCode);
			SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
			SingtonAsyncHttpClient.getInstance().get(Constants.URL_ALIPAY_PAY, params, alipayPayListener);
			CrashHandler.d(TAG, "url = " + Constants.URL_ALIPAY_PAY + "?" + params);
		}
	}
	
	/**
	 * 获取微信支付数据
	 * @param orderCode 订单号
	 * @param wechatPayListener 回调监听器
	 */
	public void wechatPay(String orderCode, WechatPayListener wechatPayListener) {
		if(!Tools.hasInternetConnection(mContext)) {
			wechatPayListener.onNoNetWork();
			
		}else {
			RequestParams params = new RequestParams();
			params.put("sn", orderCode);
			SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
			SingtonAsyncHttpClient.getInstance().get(Constants.URL_WECHAT_PAY, params, wechatPayListener);
			CrashHandler.d(TAG, "url = " + Constants.URL_WECHAT_PAY + "?" + params);
		}
	}
}
